<template>
  <section class="app-inner">
    <el-card class="header-card">
      <el-form :inline="true" :model="queryParams" size="small" label-width="84px" class="searchWrapper">
        <el-form-item>
        <el-button v-if="checkAuthority('/classes/add')" type="primary" @click="addClassFn">新增班级</el-button>

        <el-upload
          style="display: inline; margin-left: 10px"
          :show-file-list="false"
          action="no"
          :before-upload="beforeUpload"
          :http-request="importExcel"
        >
        <el-button v-if="checkAuthority('/classes/export')" type="primary" icon="import">批量导入</el-button>
        </el-upload>

        <el-button v-if="checkAuthority('/classes/download')" type="primary" @click="downFile" class="outputBtn">下载模板</el-button>
        <el-button v-if="checkAuthority('/classes/export')" type="primary" @click="exportFn" class="outputBtn">导出数据</el-button>
        <el-button v-if="checkAuthority('/classes/replace')" type="primary" @click="refreshFn">更新年级</el-button>
        </el-form-item>

        <!-- <el-form-item label="年级">
          <el-select
            v-model="queryParams.gradeName"
            clearable
            placeholder="请选择年级"
            filterable
          >
            <el-option
              v-for="item in gradeList"
              :key="item.no"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item class="inputCss">
          <el-input clearable placeholder="请输入班级名称" v-model="queryParams.className"></el-input>
        </el-form-item>

        <el-form-item>
          <el-input clearable placeholder="请输入班主任姓名" v-model="queryParams.headerName"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 底部 -->
    <el-card class="table-card">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="当前班级信息" name="nowClass"></el-tab-pane>
        <el-tab-pane label="历史班级快照" name="historyClass"></el-tab-pane>
      </el-tabs>

      <div class="leftMenu">
        <el-menu
          ref="elMenu"
          :default-active="activeIndex"
          mode='vertical'
          class="el-menu-vertical-demo"
          >
          <el-submenu index="1">
            <template slot="title">
              <span @click="searchAll">{{treeTitle}}</span>
            </template>
            <el-menu-item-group v-model='selectItem'>
              <div @click="handleChang" class="div">
                <el-menu-item :index="item.gradeName" v-for="item in treeList" :id="item.gradeName" :key="item.gradeName">
                  <span :id="item.gradeName">{{item.gradeName}}</span>
                </el-menu-item>
              </div>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </div>

      <div class="rightTable">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column type="index" label="序号" width="100"></el-table-column>
          <el-table-column prop="name" label="班级名称" width="120"></el-table-column>
          <el-table-column prop="headName" label="班主任" width="120"></el-table-column>
          <el-table-column prop="gradeName" label="年级" width="120"></el-table-column>
          <el-table-column prop="period" label="学段" width="120">
            <template  slot-scope="scope">
              <span>{{scope.row.period === '1' ? '小学' :
                scope.row.period === '2' ? '初中' : ''}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="year" label="入学年份" width="120"></el-table-column>
          <el-table-column prop="classSize" label="班级人数" width="120"></el-table-column>
          <el-table-column prop="classRoom" label="教室" width="120"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="checkAuthority('/select')" type="text" size="small" @click="handleRead(scope.row)">查看</el-button>
              <el-button v-if="checkAuthority('/classes/editor')" type="text" size="small" :disabled="classFlag" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" v-if="checkAuthority('/classes/manage') && !classFlag" @click="handleManage(scope.row)">学生管理</el-button>
              <!-- <el-button type="text" size="small" v-else @click="handleManage(scope.row)">查看学生</el-button> -->
              <el-button v-if="checkAuthority('/classes/delete')" type="text" size="small" :disabled="classFlag" @click="handleRemove(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          class="paginationCss"
          v-if="tableData.length > 0"
          layout="total, prev, pager, next"
          @current-change="changePage"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="totalCount"
        ></el-pagination>
      </div>
    </el-card>

    <add-class v-if="addClassFlag" ref="addClassModel"></add-class>
    <base-class-info ref='baseClassInfo'></base-class-info>
    <editor-class ref="editorClass" @ok="editOk"></editor-class>
    <student-manage ref="studentManage"></student-manage>
  </section>
</template>

<script>
import Vue from 'vue'
import addClass from './components/addClass.vue'
import baseClassInfo from './components/baseClassInfo.vue'
import editorClass from './components/editorClass.vue'
import studentManage from './components/studentManage.vue'
import { getClass, batchAddClass, exportClass, updatedClass, removeClass, downClassTemplate } from './js/class.js'
import { sepDataDicInfoQuery } from './js/controllerInfo.js'
import { checkAuthority } from '@/utils/btnPermission' // 页面按钮权限
export default {
  name: 'classInfo',
  components: {
    addClass,
    baseClassInfo,
    editorClass,
    studentManage
  },
  data () {
    return {
      activeName: 'nowClass',
      // gradeList: [], // 年级下拉框列表
      queryParams: {
        className: '',
        gradeName: '',
        headerName: '',
        pageNum: 1,
        pageSize: 10,
        status: 1
      },
      addClassFlag: false,
      activeIndex: '1',
      selectItem: '',
      treeList: [],
      treeTitle: '',
      // eqptTypeList: [],
      totalCount: 0,
      tableData: [],
      classFlag: false
    }
  },
  watch: {
    addClassFlag (val) {
      if (val === false) {
        let query = {
          ...this.queryParams,
          pageNum: 1,
          pageSize: 10
        }
        this.getClassList(query)
      }
    }
  },
  methods: {
    checkAuthority,
    // 新增班级
    addClassFn () {
      this.addClassFlag = true
    },

    // 搜索
    search () {
      // 如果班级名称和班主任名称都没有时，清空 左侧树 选中效果
      if (!this.queryParams.className && !this.queryParams.headerName) {
        this.$refs.elMenu.activeIndex = null
      }
      // 获取全部数据
      let queryParams = {
        ...this.queryParams,
        pageNum: 1,
        pageSize: 10
      }
      this.getClassList(queryParams)
      this.queryParams.pageNum = 1
      // this.activeIndex = ''
    },

    // 导入前的验证
    beforeUpload (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!extension && !extension2) {
        this.$message.warning('上传模板只能是 xls、xlsx格式!')
        return false
      } else if (!isLt2M) {
        this.$message.warning('上传模板大小不能超过 5MB!')
        return false
      } else {
        return true
      }
    },

    // EXCEL导入
    importExcel (file, fileList) {
      let headFile = file.file
      let formData = new FormData()
      formData.append('file', headFile)
      batchAddClass(formData).then((res) => {
        let query = {
          pageNum: 1,
          pageSize: 10,
          status: this.queryParams.status
        }
        this.getClassList(query)
        this.$message.success('导入成功')
      })
    },

    // 下载模板
    async downFile () {
      try {
        let res = await downClassTemplate()
        if (res.code === 0) {
          this.$message.success('下载中')
        }
      } catch (e) {}
    },

    // 导出
    async exportFn () {
      try {
        let res = await exportClass(this.queryParams)
        if (res.code === 0) {
          this.$message.success('导出成功！')
        } else {
          this.$message.error(res.msg)
        }
      } catch (e) {}
    },

    // 更新年级
    async refreshFn () {
      try {
        let res = await updatedClass()
        if (res.code === 0) {
          let query = {
            pageNum: 1,
            pageSize: 10,
            status: this.queryParams.status
          }
          this.getClassList(query)
          this.$message.success('更新成功')
        } else {
          this.$message.error(res.msg)
        }
      } catch (e) {}
    },

    // 切换选项卡 当前班级信息 、历史班级快照
    async handleClick (e) {
      this.$refs.elMenu.activeIndex = null
      this.queryParams.pageNum = 1
      this.queryParams.gradeName = '' // 左侧树选中值 置空
      if (e.name === 'historyClass') {
        this.classFlag = true // 历史快照时，编辑、删除等功能不可用 标识
        this.queryParams.status = 0 // 班级状态为 0：失效
        try {
          let query = {
            ...this.queryParams,
            pageNum: 1,
            pageSize: 10
          }
          this.getClassList(query)
        } catch (e) {}
      } else {
        this.classFlag = false // 当前班级信息，编辑、删除等功能可用 标识
        this.queryParams.status = 1 // 班级状态为 1：有效
        try {
          this.getClassList(this.queryParams)
        } catch (e) {}
      }
    },

    // 点击一级树  ‘黄卢一小’ 搜索全部内容
    searchAll () {
      // 清空搜索条件
      this.queryParams.className = ''
      this.queryParams.headerName = ''
      this.queryParams.pageNum = 1
      // 清空左侧 树选择状态
      this.$refs.elMenu.activeIndex = null
      let query = {
        pageNum: 1,
        pageSize: 10,
        status: this.queryParams.status
      }
      this.getClassList(query)
    },

    // 更改左侧菜单
    handleChang (e) {
      this.queryParams.gradeName = e.target.id
      this.queryParams.pageNum = 1
      let queryParams = {
        ...this.queryParams,
        pageSize: 10
        // gradeName: e.target.id
      }
      this.getClassList(queryParams)
    },

    // 更改页数
    changePage (val) {
      this.queryParams.pageNum = val
      this.getClassList(this.queryParams)
    },

    // 查看详情
    async handleRead (row) {
      this.$refs.baseClassInfo.add(row)
    },

    // 编辑
    handleEdit (row) {
      this.$refs.editorClass.add(row)
    },

    editOk () {
      this.$message.success('保存成功！')
      this.getClassList(this.queryParams)
    },

    // 学生管理
    handleManage (row) {
      /*
      classFlag true：历史快照，false：当前班级信息
      row.flag 0: 当前班级信息，学生管理中按钮皆可用
      row.flag 1: 历史快照，学生管理中按钮只有导出可用
      */
      row.flag = this.classFlag ? 0 : 1
      row.status = this.queryParams.status
      this.$refs.studentManage.add(row)
    },

    // 删除班级
    async handleRemove (row) {
      let classNo = row.classNo
      this.orderDelete(classNo)
    },

    // 确定删除弹窗
    async orderDelete (ids) {
      this.$confirm('确定删除该班级吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let result = await removeClass(ids)
        if (result.code === 0) {
          this.$message.success('删除成功！')
          await this.getClassList(this.queryParams)
        } else {
          this.$message.error(result.msg + '删除失败！')
        }
      })
    },

    // 获取班级列表请求
    async getClassList (data) {
      let res = await getClass(data)
      if (res.code === 0) {
        let { data } = res
        this.tableData = data.classList.records
        this.totalCount = data.classList.total
        this.treeTitle = data.schoolName
        this.treeList = data.classGradeList
      } else {
        this.$message({
          type: 'error',
          message: '暂无数据'
        })
      }
    },

    // 数据字典
    async getSepDataDicInfoQuery () {
      let res = await sepDataDicInfoQuery()
      Vue.prototype.$dictionary = res.data
    }
  },

  async mounted () {
    await this.getSepDataDicInfoQuery()
    this.getClassList(this.queryParams)
  }
}
</script>

<style scoped lang="scss">
.header-card {
  vertical-align: middle;
}
.outputBtn {
  margin-left: 10px;
}
.searchWrapper {
  display: inline-block;
  // margin-left: 50px;
  // width: 300px;
  // vertical-align: middle;
}
// .el-menu-vertical-demo {
//   width: 20%;
// }
/deep/ .el-submenu__title {
  width: 140px;
}
.table-card {
  .leftMenu {
    display: inline-block;
    width: 11%;
  }
  .rightTable {
    float: right;
    // display: inline-block;
    width: 89%;
  }
}
.el-submenu .el-menu-item {
  min-width: 100px;
}
.paginationCss {
  float: right;
}
.el-menu-item >>> .is-active {
  width: 80px;
}
.el-submenu >>> .is-active {
  width: 80px;
}
.inputCss {
  margin-left: 30px;
}
/deep/ .el-menu {
  margin-left: -5%;
}
/deep/ .el-menu-item-group {
  margin-left: 10px;
}
</style>
